<template>
	<view class="scan-container">
		<view id="scan-reader"></view>
	</view>
</template>

<script setup>
	import { onMounted,onUnmounted, ref } from 'vue';
	import { Html5Qrcode,Html5QrcodeScanType,Html5QrcodeSupportedFormats} from 'html5-qrcode'
	
	const props = defineProps({
		qrbox: {
			type: Number,
			default: 250
		},
		fps: {
			type: Number,
			default: 10
		}
	})
	const emits = defineEmits(['result','fail'])
	
	let html5QrCode = null
	
	onMounted(()=>{
		setTimeout(()=>{
			getCamerasConfig()
		},500)
	})
	onUnmounted(()=>{
		stopScan()
	})
	//获取摄像头权限
	const getCamerasConfig = () => {
		Html5Qrcode.getCameras().then((devices) => {
			if (devices && devices.length) {
				startScan()
			}
		}).catch((err) => {
			uni.$tools.showToast('获取设备信息失败')
			uni.navigateBack()
		})
	}
	//开始扫描
	const startScan = ()=>{
		//扫码配置信息
		const config = {
			fps: props.fps,
			qrbox: {
				width:props.qrbox,
				height:props.qrbox
			}
		}
		html5QrCode = new Html5Qrcode('scan-reader')
		html5QrCode.start({facingMode:'environment'},config,onScanSuccess,onScanFail).catch((err)=>{
			console.log('扫码失败',err)
		})
	}
	//扫描成功回调
	const onScanSuccess = (decodedText, decodedResult)=>{
		emits('result',decodedText)
	}
	//扫描失败回调
	const onScanFail = (err)=>{
		console.log('暂无扫描结果',err)
		emits('fail',err)
	}
	//停止扫描
	const stopScan = ()=> {
		if(html5QrCode){
			html5QrCode.stop().then((ignore)=>{
				console.log('QRCode scanning stopped')
			}).catch((err)=>{
				console.log('Unable to stop scanning,',err)
			})
		}
	}
	
</script>

<style lang="scss" scoped>
.scan-container{
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100vh;
	background-color: rgba(0, 0, 0, 0.48);
	z-index: 9999;
	#scan-reader{
		top: 50%;
		left: 0;
		transform: translateY(-50%);
	}
}
</style>